package cn.demoncat.util.web.cloud.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

/**
 * 通用的 GatewayFilter
 *
 * 1、截取URL前缀（相当于 StripPrefix=1 ）
 * 2、禁止请求 /rest/ 和 /actuator/
 *
 * @author 延晓磊
 * @since 2022年10月27日
 */
@Component
public class CommonGatewayFilter extends AbstractGatewayFilterFactory<CommonGatewayFilter.Config> {

    /**
     * 指定配置类型
     */
    public CommonGatewayFilter() {
        super(Config.class);
    }

    /**
     * 定义配置名称
     */
    @Override
    public String name() {
        return "Common";
    }

    /**
     * 网关拦截
     */
    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            // 获取URL
            String url = exchange.getRequest().getURI().getRawPath();
            // 截取前缀
            url = url.substring(url.indexOf("/", 1));
            // 禁止REST请求
            if (url.startsWith("/rest/") || url.startsWith("/actuator/")) {
                exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
                return exchange.getResponse().setComplete();
            }
            // 变更请求
            ServerHttpRequest request = exchange.getRequest().mutate().path(url).build();
            exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR, request.getURI());
            return chain.filter(exchange.mutate().request(request).build());
        };
    }

    /**
     * 配置参数
     */
    public static class Config {

    }
}
